package com.kll.tv

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.util.Log
import androidx.camera.camera2.Camera2Config
import androidx.camera.core.CameraXConfig
import androidx.core.content.FileProvider
import androidx.multidex.MultiDex
import com.google.gson.Gson
import com.kll.carolinehmibiz.BaseApplication
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.common.constant.FontConstants
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.DownloadFileProgress
import com.kll.carolinehmibiz.net.bean.GetAppNewlyVersionResponse
import com.kll.carolinehmibiz.base.utils.L
import com.kll.tv.utils.ProcessUtils
import java.io.File


/**
 * ====================================================
 * Created by Ziliang Cai on 2021/12/7 22:31
 * <a href="mailto:752777456@qq.com">Contact me</a>
 * ====================================================
 */
class MyApplication : BaseApplication(), CameraXConfig.Provider {

    companion object {
        private lateinit var mInstance: MyApplication

        fun getInstance(): MyApplication {
            return mInstance
        }

        private fun getAllCommand(command: ArrayList<String>, file: File?) {
            if (file == null) {
                return
            }
            command.add("chmod 777 " + file.absolutePath)
            getAllCommand(command, file.parentFile)
        }


    }

    override fun onCreate() {
        super.onCreate()
        L.setDEBUG(true)
        MultiDex.install(this)
        FontConstants.init(this)
        mInstance = this

        initTui()
    }

    /**
     * 发现了新版本
     */
    override fun onNewlyVersion(versionInfo: GetAppNewlyVersionResponse) {
        L.e(
            ">>>>>>",
            "MyApplication>>onNewlyVersion:: 发现了新版本: ${versionInfo.version} - ${versionInfo.versioncode}"
        )
        L.e(">>>>>>", "MyApplication>>onNewlyVersion:: 新apk url: ${versionInfo.url}")


        // 开始下载文件
        var dataFile = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            dataFile = "${filesDir.absolutePath}/${System.currentTimeMillis()}.apk"
        } else {
            dataFile =
                "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)}/${System.currentTimeMillis()}.apk"
        }

        L.e(">>>>>>", "MyApplication>>onNewlyVersion:: data path = $dataFile")

        OperationManager.getInstancce()
            .downloadFile(versionInfo.url, dataFile, object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    L.e(
                        ">>>>>>",
                        "MyApplication>>onNewlyVersion>>onSuccess:: obj = ${Gson().toJson(obj)}"
                    )

                    var data = obj as DownloadFileProgress

                    if (data.isFinshed) {
                        install(dataFile)
                    }
                }

                override fun onFail(code: Int, message: String) {
                    L.e(">>>>>>", "MyApplication>>onNewlyVersion>>onFail")
                }

            })

//        var dataFile = "/data/data/com.kll.tv/files/1641828357437.apk"
//        install(dataFile)

    }

    private fun initTui() {

    }

//    private fun install(apkFile: File) {
////        var apk = File(...);
//        var uri = Uri.fromFile(apkFile);
//        var intent = Intent()
//        intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
//        intent.data = uri;
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startActivity(intent);
//    }

    fun install(apkFile: String) {

//        if (apkFile == null || !apkFile.exists()) {
//            return
//        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            openInstallPage(apkFile)
//        } else {
//            // 这一步很重要，android 6.0 及以下，需要获取文件全路径的文件权限
//            chmodFullFile(this, apkFile)
//        }

        openInstallPage(apkFile)
    }

    /**
     * 修改file全路径的读写权限
     *
     * @param file
     */
    private fun chmodFullFile(context: Context, file: String) {
//        if (file == null) {
//            return
//        }
        val commands: ArrayList<String> = ArrayList()
//        getAllCommand(commands, file)
        if (commands.size > 0) {
            val c = ArrayList<String>()
            for (i in 0 until c.size) {
                c.add(commands[i])
//                c[i] = commands[i]
                println(commands[i])
            }
            ProcessUtils.executeProcess(c, null, 5000, object : ProcessUtils.ProcessListener {
                override fun finish() {
                    openInstallPage(file)
                }
            })
        }
    }

    /**
     * 打开apk安装界面
     *
     * @param context
     * @param apkUri
     */
    private fun openInstallPage(apkPath: String) {

        L.e("----", "apkUri = ${apkPath}")

        try {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//            var uri: Uri

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                var uri = FileProvider.getUriForFile(this, "com.kll.tv.fileprovider", File(apkPath))
                intent.setDataAndType(uri, "application/vnd.android.package-archive")
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            } else {
                intent.setDataAndType(
                    Uri.fromFile(File(apkPath)),
                    "application/vnd.android.package-archive"
                )
            }

            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @SuppressLint("UnsafeOptInUsageError")
    override fun getCameraXConfig(): CameraXConfig {
        return CameraXConfig.Builder.fromConfig(Camera2Config.defaultConfig())
            .setMinimumLoggingLevel(Log.ERROR).build();
    }
}